﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Word.Server.Service;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Word.Server.Conversions;
using System.Globalization;

namespace SP2010WordAutomation.UI.Layouts.SP2010WordAutomation.UI
{
    public partial class ConvertDocument : LayoutsPageBase
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            btnOk.Click += new EventHandler(btnOk_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindOutputLibrary();
                lblMessages.Text = "";
            }
        }

        void btnOk_Click(object sender, EventArgs e)
        {
            try {
                string source = Request["source"];
                string items = Request["items"];
                
                Microsoft.Office.Word.Server.Service.WordServiceApplicationProxy wordServiceApplicationProxy =
                    GetWordServiceApplicationProxy(SPContext.Current.Site.WebApplication);
                
                ConversionJob job = new ConversionJob(wordServiceApplicationProxy);
                job.UserToken = SPContext.Current.Web.CurrentUser.UserToken;

                job.Settings.UpdateFields = true;
                job.Settings.OutputFormat = (SaveFormat)Enum.Parse(typeof(SaveFormat), ddlOutputFormat.SelectedValue);
                job.Settings.OutputSaveBehavior = (SaveBehavior)Enum.Parse(typeof(SaveBehavior), ddlSaveBehaviour.SelectedValue);

                string targetExtension = ".pdf";
                switch (job.Settings.OutputFormat)
                { 
                    case SaveFormat.Document:
                        targetExtension = ".docx";
                        break;
                    case SaveFormat.Document97:
                        targetExtension = ".doc";
                        break;
                    case SaveFormat.PDF:
                        targetExtension = ".pdf";
                        break;
                    case SaveFormat.RTF:
                        targetExtension = ".rtf";
                        break;                   
                    case SaveFormat.XPS:
                        targetExtension = ".xps";
                        break;
                }

                string messages = AddFiles(items, new System.Guid(source), new Guid(ddlOutputLibrary.SelectedValue), job, targetExtension);

                try
                {
                    job.Start();
                }
                catch (Exception)
                { 
                    //  Job can fail if it doesn't contain any items
                }

                string conversionJobId = job.JobId.ToString();

                if (string.IsNullOrEmpty(messages))
                {

                    this.Page.Response.Clear();
                    this.Page.Response.Write(string.Format(CultureInfo.InvariantCulture,
                                "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, 'Document Conversion Job {0} started');</script>", conversionJobId));
                    this.Page.Response.End();
                }
                else {
                    lblMessages.Text = messages;                    
                }
            }
            catch (Exception) 
            { }
        }

        private string AddFiles(string items, Guid sourceLibraryId, Guid outputLibraryId, ConversionJob job, string targetExtension)
        {
            SPList sourceLibrary = SPContext.Current.Web.Lists[sourceLibraryId];
            SPList outputLibrary = SPContext.Current.Web.Lists[outputLibraryId];

            string[] itemids = items.Trim('|').Split('|');
            string messages = "";

            foreach (string itemid in itemids)
            {
                try
                {
                    SPListItem item = sourceLibrary.GetItemById(int.Parse(itemid));
                    string targetFileName = System.IO.Path.GetFileNameWithoutExtension(item.File.Name) + targetExtension;
                    string targetFileUrl = SPContext.Current.Web.Url + "/" + outputLibrary.RootFolder.Url + "/" + targetFileName;

                    try
                    {

                        job.AddFile(SPContext.Current.Site.Url + item.File.ServerRelativeUrl, targetFileUrl);
                    }
                    catch (Exception ex)
                    {
                        messages += "<br/>" + ex.Message;
                    }
                }
                catch (Exception)
                { }
            }

            return messages;
        }

        private void BindOutputLibrary()
        {
            try
            {
                foreach (SPList list in SPContext.Current.Web.Lists)
                {
                    if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                    {
                        try
                        {
                            list.CheckPermissions(SPBasePermissions.AddListItems);

                            ddlOutputLibrary.Items.Add(new System.Web.UI.WebControls.ListItem(list.Title, list.ID.ToString()));
                        }
                        catch (UnauthorizedAccessException)
                        { }
                    }
                }
            }
            catch (Exception)
            { }
        }

        internal static Microsoft.Office.Word.Server.Service.WordServiceApplicationProxy GetWordServiceApplicationProxy(Microsoft.SharePoint.Administration.SPWebApplication webApplication)
        {
            if (!webApplication.ServiceApplicationProxyGroup.ContainsType(typeof(WordServiceApplicationProxy)))
            {
                throw new Exception("No WordServiceApplicationProxy associated with this SPWebApplication");
            }
            else
            {
                foreach (SPServiceApplicationProxy proxy in webApplication.ServiceApplicationProxyGroup.Proxies)
                {
                    if (proxy.GetType() == typeof(WordServiceApplicationProxy))
                        return (WordServiceApplicationProxy)proxy;
                }
                return null;
            }
        }
    }
}
